package cn.xiaopengstack.infrastructure.event;

import cn.xiaopengstack.types.event.BaseEvent;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author jiangyangang
 */
@Slf4j
@Service
public class EventPublish {

    @Resource
    private RocketMQTemplate rocketMQTemplate;

    public void publish(BaseEvent<?> event){
        BaseEvent.EventMessage<?> playlod = event.playlod();
        try {
            rocketMQTemplate.convertAndSend(event.topic(), playlod);
            log.info("发送MQ消息成功，topic={}, message={}", event.topic(), playlod);
        } catch (Exception e) {
            log.error("发送MQ消息失败 topic={} message={}", event.topic(), JSONObject.toJSONString(playlod), e);
            throw e;
        }
    }

    /**
     * 发送消息
     * @param payload 消息
     * @param topic topic
     */
    public void publish(String payload, String topic){
        try {
            rocketMQTemplate.convertAndSend(topic , payload);
            log.info("发送MQ消息成功 topic={} message={}", topic, JSONObject.toJSONString(payload));
        } catch (Exception e) {
            log.error("发送MQ消息失败 topic={} message={}", topic, JSONObject.toJSONString(payload), e);
            throw e;
        }
    }
}
